<template>
	<view class="y-flex y-flex-1">
		<com-swiper-list
		ref="swiperList"
		enable-scroll-event
		:top="windowTop"
		:data="subsection"
		:tabs-show="subsection.length > 1"
		:enableSwiper="enableSwiper"
		:refreshImage="pageStyle.pulldownRefreshImage"
		:pulldownable="pageStyle.enablePulldown == 1"
		:column="subsectionColumn"
		:current="subsectionSelectedIndex"
		:bg-color="subsectionBackgroundColor"
		:text-color="skinColor.color_1"
		:border-color="skinColor.color_gap_1"
		:selected-color="subsectionSelectedColor"
		@scroll="handleScroll"
		@pulldown="handlePulldown(subsectionSelectedIndex, $event)"
		@change="handleTabsChange">
			<template #top>
				<com-image enable-preview class="find-user-cover" :src="detail.cover" mode="aspectFill"></com-image>
				<view class="find-user-info page-padding-gap">
					<view class="y-flex y-align-center">
						<view class="find-user-avatar" elevation="3px" :style="{'border-color': skinColor.color_bg_1, 'background-color': skinColor.color_bg_1}">
							<com-avatar enable-preview :src="detail.avatar" :size="180"></com-avatar>
						</view>
						<com-gap height="40rpx"></com-gap>
					</view>
					<view class="y-flex y-align-center">
						<text class="fs-40 fw-bold text-align-center" :style="{color: skinColor.color_1}">{{detail.title}}</text>
						<text class="fs-24 text-align-center mt-10" :style="{color: skinColor.color_2}" v-if="detail.subtitle">{{detail.subtitle}}</text>
						<com-read-more class="mt-20" :shadow-color="skinColor.color_bg_1" v-if="detail.description">
							<text class="fs-28" selectable :style="{color: skinColor.color_2}">{{detail.description}}</text>
						</com-read-more>
						<scroll-view class="y-flex y-row y-align-center mt-20" :show-scrollbar="false" scroll-x v-if="detail.tags && detail.tags.length">
							<view class="find_novel_tag mr-20" v-for="(item, index) in detail.tags" :key="index" :style="{'border-color': themeColor}" @tap="handleTagTap(item)">
								<text class="fs-24" :style="{color: themeColor}">{{item.title}}</text>
							</view>
						</scroll-view>
						<mp-html class="mt-20" selectable :copy-link="false" :content="content" @linktap="handleLinkTap" v-if="content"></mp-html>
					</view>
					<com-gap></com-gap>
				</view>
			</template>
			<template v-slot="{swiper, i}">
				<module-list :ref="'list' + i"
				:component="swiper.components"
				:cell="swiper.cell"
				:params="moduleParams"
				:bounce="swiper.style.enableBounce"
				:loadmoreable="swiper.style.enableLoadmore == 1"
				:back-top-show="swiper.style.enableBackTop"
				:backTopImage="swiper.style.backTopImage"
				:loadingColor="swiper.style.loadingColor"
				@pulldown="handleGetData(i, $event)"
				@loaded="handleModuleLoaded(i)">
				</module-list>
			</template>
		</com-swiper-list>
	</view>
</template>

<script>
	import ModuleList from './components/ModuleList.vue'
	import { openDB, closeDB, select, remove, insert } from '@/assets/database'
	import { pixelunit } from '@/assets/js/util.js'
	export default {
		inject: ['getPage', 'getPageStyle', 'getSkinColor', 'getQuery', 'getSkinMode', 'sharePoster', 'navigate'],
		components: {
			ModuleList
		},
		computed: {
			skinColor () {
				return this.getSkinColor()
			},
			skinMode () {
				return this.getSkinMode()
			},
			//获取路由参数
			query () {
				return this.getQuery()
			},
			$Route () {
				return getApp().globalData.$Route
			},
			page () {
				return this.getPage()
			},
			pageStyle () {
				return this.getPageStyle()
			},
			network () {
				return this.$store.getters['network/GET']
			},
			//选项栏栏数
			subsectionColumn () {
				return this.pageStyle.subsectionColumn || 'auto'
			},
			//选项栏背景色
			subsectionBackgroundColor () {
				return this.pageStyle.subsectionBackgroundColor || this.skinColor.color_bg_1
			},
			//选项栏选中高亮色
			subsectionSelectedColor () {
				return this.pageStyle.subsectionSelectedColor || this.themeColor
			},
			//开启左右滑动
			enableSwiper () {
				return this.pageStyle.enableSwiper || false
			},
			windowTop () {
				const navHeight = this.pageStyle.enableNavigationTransparent ? uni.getSystemInfoSync().safeArea.top + uni.upx2px(100) : 0
				return navHeight + 'px'
			},
			//主题色
			themeColor () {
				return this.pageStyle.themeColor || this.skinColor.color_blue
			},
			content () {
				return this.detail.content ? `<div style="color: ${this.skinColor.color_1}">` + this.detail.content + '</div>' : ''
			},
			moduleParams () {
				return {...this.detail, ...this.query}
			}
		},
		data () {
			return {
				detail: {},
				subsection: [],
				subsectionSelectedIndex: 0//选项栏选中索引
			}
		},
		mounted() {
			this.$nextTick(() => {
				this.refresh()
			})
		},
		methods: {
			refresh () {
				this.handleGetSubsection()
			},
			onShow () {
				if ( this.detail.uniqueId ) this.getFollowee()
			},
			handleScroll (e) {
				this.$emit('scroll', Math.abs(e.contentOffset.y))
			},
			handleModuleLoaded () {
				this.$refs.swiperList && this.$refs.swiperList.pulldownSuccess()
			},
			async handlePulldown (key, callback) {
				try{
					this.detail = await this.handleGetDetail()
					this.$emit('loaded', true)
					this.$refs['list' + key] && this.$refs['list' + key].initModule(null, callback || !this.enableSwiper)
					this.$refs.swiperList && this.$refs.swiperList.setSpecialEffects()
					if ( this.detail.uniqueId ) this.getFollowee()
				}catch(e){
					this.$emit('loaded', true)
				}
			},
			getFollowee () {
				openDB().then(async () => {
					try{
						const data = await select('followee', 'unique_id = "' + this.detail.uniqueId + '"')
						const utils = [{
							label: data.count > 0 ? '已关注' : '关注他',
							icon: data.count > 0 ? 'people_fill' : 'people',
							color: data.count > 0 ? this.skinColor.color_red : '',
							func: () => {
								if ( data.count > 0 ) {
									openDB().then(() => {
										remove('followee', 'id = ' + data.list[0].id).then(() => {
											uni.showToast({
												title: '取消关注成功',
												icon: 'none'
											})
											closeDB().then(() => {
												this.getFollowee()
											})
										}).catch(err => {
											closeDB()
											uni.showToast({
												title: err.message,
												icon: 'none'
											})
										})
									})
								} else {
									const params = {
										unique_id: this.detail.uniqueId,
										url: this.detail.url,
										title: this.detail.title || '',
										avatar: this.detail.avatar || '',
										is_adult: this.detail.isAdult || 0,
										source_id: this.detail.sourceId
									}
									openDB().then(() => {
										insert('followee', params).then(() => {
											uni.showToast({
												title: '关注成功',
												icon: 'none'
											})
											closeDB().then(() => {
												this.getFollowee()
											})
										}).catch(err => {
											closeDB()
											uni.showToast({
												title: err.message,
												icon: 'none'
											})
										})
									})
								}
							}
						}]
						if ( this.detail.shareUrl && this.detail.title ) {
							utils.push({
								label: '推荐他',
								icon: 'bar_code',
								func: () => {
									this.sharePoster(this.detail)
								}
							})
						}
						this.$emit('utils', utils)
					}catch(e){
						uni.showToast({
							title: e.message,
							icon: 'none'
						})
					}
					closeDB()
				})
			},
			async handleGetSubsection () {
				this.subsectionSelectedIndex = this.query.selected || 0
				const subsection = this.page?.subsection || []
				this.subsection = subsection.map(s => Object.assign({}, s, {style: Object.assign({}, this.pageStyle, s.style, this.skinMode == 'night' ? {} : (s.darkStyle || {}))}))
				this.$nextTick(function () {
					setTimeout(() => {
						this.handlePulldown(this.subsectionSelectedIndex)
					}, 100)
				})
			},
			async handleGetDetail () {
				const detail = this.page?.detail || {}
				const staticData = await this.network.staticDataHandle(detail.staticData || {}, this.query)
				const dynamicData = detail.dynamicData
				const request = detail.request
				const routeUrl = this.$Route.query.routeUrl
				let data = {}
				if ( dynamicData && request ) {
					const newRequest = await this.network.requestHandle(request, this.query)
					const response = await this.network.$request(newRequest)
					data = await this.network.$list(dynamicData, response.data, response.taskId)
					data.uniqueId = data.id || this.network.getUniqueId(newRequest)
					if ( !data.shareUrl && !staticData.shareUrl ) data.shareUrl = await this.network.getShareUrl(newRequest)
				}
				return Object.assign({}, {shareType: 'user'}, staticData, data)
			},
			handleTabsChange (e) {
				if ( this.changeTimer ) {
					clearTimeout(this.changeTimer)
					this.changeTimer = null
				}
				this.subsectionSelectedIndex = e.current
				this.$nextTick(function () {
					const key = this.subsectionSelectedIndex
					this.changeTimer = setTimeout(() => {
						this.handlePulldown(key)
					}, 300)
				})
			},
			handleLinkTap (e) {
				this.navigate(e.href)
			}
		}
	}
</script>

<style>
	.find-user-cover {
		height: 230rpx;
	}
	.find-user-info {
		margin-top: -90rpx;
	}
	.find-user-avatar {
		border-style: solid;
		border-width: 5rpx;
		border-radius: 120rpx;
	}
</style>